package com.ruoyi.web.controller.system;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.ruoyi.common.enums.BacklogStatus;
import com.ruoyi.common.enums.TenantStatus;
import com.ruoyi.common.enums.TenantUsedType;
import com.ruoyi.common.utils.DoubleUtil;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.util.ShiroUtils;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.service.*;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 租户收租待办Controller
 * 
 * @author ruoyi
 * @date 2020-07-20
 */
@Controller
@RequestMapping("/system/backlog")
public class SysTenantBacklogController extends BaseController
{
    private String prefix = "system/backlog";

    @Autowired
    private ISysTenantBacklogService sysTenantBacklogService;

    @Autowired
    private ISysTenantService tenantService;

    @Autowired
    private ISysExpenseService expenseService;

    @Autowired
    private ISysExpenseMergeService sysExpenseMergeService;

    @Autowired
    private ISysHigherService sysHigherService;

    @RequiresPermissions("system:backlog:view")
    @GetMapping()
    public String backlog()
    {
        return prefix + "/backlog";
    }

    @GetMapping("/complete")
    public String complete()
    {
        return prefix + "/complete";
    }

    /**
     * 查询租户收租待办列表
     */
    @RequiresPermissions("system:backlog:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(SysTenantBacklog sysTenantBacklog)
    {
        startPage();
        sysTenantBacklog.setBacklogStatus(BacklogStatus.WAIT.getCode());
        List<SysTenantBacklog> list = sysTenantBacklogService.selectSysTenantBacklogMergeList(sysTenantBacklog);
        return getDataTable(list);
    }

    /**
     * 查询本月已收租列表
     */
    @PostMapping("/completeList")
    @ResponseBody
    public TableDataInfo completeList()
    {
        startPage();
        List<SysExpenseMerge> list = sysExpenseMergeService.selectSysExpenseMergeMonthList(null);
        return getDataTable(list);
    }

    /**
     * 导出租户收租待办列表
     */
    @RequiresPermissions("system:backlog:export")
    @Log(title = "租户收租待办", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(SysTenantBacklog sysTenantBacklog)
    {
        List<SysTenantBacklog> list = sysTenantBacklogService.selectSysTenantBacklogList(sysTenantBacklog);
        ExcelUtil<SysTenantBacklog> util = new ExcelUtil<SysTenantBacklog>(SysTenantBacklog.class);
        return util.exportExcel(list, "backlog");
    }

    /**
     * 新增租户收租待办
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存租户收租待办
     */
    @RequiresPermissions("system:backlog:add")
    @Log(title = "租户收租待办", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(SysTenantBacklog sysTenantBacklog)
    {
        return toAjax(sysTenantBacklogService.insertSysTenantBacklog(sysTenantBacklog));
    }

    /**
     * 修改租户收租待办
     */
    @GetMapping("/edit/{backlogId}")
    public String edit(@PathVariable("backlogId") Long backlogId, ModelMap mmap)
    {
        SysTenantBacklog sysTenantBacklog = sysTenantBacklogService.selectSysTenantBacklogById(backlogId);
        mmap.put("sysTenantBacklog", sysTenantBacklog);
        return prefix + "/edit";
    }

    /**
     * 修改保存租户收租待办
     */
    @RequiresPermissions("system:backlog:edit")
    @Log(title = "租户收租待办", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(SysTenantBacklog sysTenantBacklog)
    {
        return toAjax(sysTenantBacklogService.updateSysTenantBacklog(sysTenantBacklog));
    }

    /**
     * 删除租户收租待办
     */
    @RequiresPermissions("system:backlog:remove")
    @Log(title = "租户收租待办", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(sysTenantBacklogService.deleteSysTenantBacklogByIds(ids));
    }

    /**
     * 跳转收租页面
     */
    @GetMapping("/confirm/{tenantId}/{backlogId}")
    public String confirm(@PathVariable("tenantId") String tenantId, @PathVariable("backlogId") String backlogId, ModelMap mmap)
    {
        Double higherRentFee = 0D;
        SysTenant sysTenant = tenantService.selectSysTenantBacklogByIds(tenantId);
        sysTenant.setMonthlyRentFee(String.valueOf(DoubleUtil.round(Double.parseDouble(sysTenant.getMonthlyRentFee()),2)));
        if(StringUtils.isNotBlank(sysTenant.getPropertyFee())){
            sysTenant.setPropertyFee(String.valueOf(DoubleUtil.round(Double.parseDouble(sysTenant.getPropertyFee()),2)));
        }

        SysExpenseMerge sysExpenseMerge = new SysExpenseMerge();
        BeanUtils.copyProperties(sysTenant,sysExpenseMerge);
        //计算合同涨租后应收租金
//        List<SysHigher> higherList = sysHigherService.selectSysHigherLogByTenantIdsList(sysExpenseMerge.getTenantIdStr());
//        double higherRentFee = 0;
//        for (SysHigher sysHigher : higherList) {
//            higherRentFee+=sysHigher.getHigherRentFee();
//        }
        if(!sysTenant.getHigherRentFee().isEmpty()){
            higherRentFee = Double.parseDouble(sysTenant.getHigherRentFee());
        }else {
            higherRentFee = 0D;
        }
        mmap.put("higherRentFee",DoubleUtil.round(higherRentFee,2));

        //查询上月电表和上月水表度数
        SysExpenseMerge sysExpenseMergeTemp = sysExpenseMergeService.selectSysExpenseMergeByTenantId(tenantId);
        if (sysExpenseMergeTemp!=null){
            if(StringUtils.isNotBlank(sysExpenseMergeTemp.getLastMonthEletableNumber())){
                sysExpenseMerge.setLastMonthEletableNumber(sysExpenseMergeTemp.getThisMonthEletableNumber());
            }
            if(StringUtils.isNotBlank(sysExpenseMergeTemp.getLastMonthWatableNumber())){
                sysExpenseMerge.setLastMonthWatableNumber(sysExpenseMergeTemp.getThisMonthWatableNumber());
            }
        }
        mmap.put("sysExpenseMerge", sysExpenseMerge);

        //传入公摊比例
        float apportionRatio = 0;
        float allArea = 0;
        if(sysTenant != null){
            //TODo
            SysTenant sysTenantAppro = new SysTenant();
            sysTenantAppro.setTenantStatus(TenantStatus.LIVEING.getCode());

            List<SysTenant> list = new ArrayList<>();
            SysTenant sysTenantArea = new SysTenant();
            if(sysTenant.getTenantUse().equals(TenantUsedType.ACCOMMODATION.getCode())){
                //宿舍总面积
                sysTenantArea = tenantService.selectSysTenantAccommodationArea();
            }else {
                //个人或者企业总面积
                sysTenantArea = tenantService.selectSysTenantOtherArea();
            }

            apportionRatio = Float.parseFloat(sysExpenseMerge.getTenantArea())/Float.parseFloat(sysTenantArea.getTenantArea());
        }
        mmap.put("apportionRatio",apportionRatio);
        String apportionRatioTemp = DoubleUtil.round(apportionRatio*100,2)+"%";
        mmap.put("apportionRatioTemp",apportionRatioTemp);
        //传入待收租ID
        mmap.put("backlogId",backlogId);
        return prefix + "/confirm";
    }

    /**
     * 确认收租
     */
    @RequiresPermissions("system:backlog:confirm")
    @Log(title = "确认收租", businessType = BusinessType.INSERT)
    @PostMapping("/confirm")
    @ResponseBody
    public AjaxResult confirmSave(SysExpenseMerge sysExpenseMerge, String backlogId,String tenantIdStr) {
        sysExpenseMerge.setCreateBy(ShiroUtils.getLoginName());
        ShiroUtils.clearCachedAuthorizationInfo();
//        sysExpenseMerge = sysExpenseMergeService.selectSysExpenseMergeByTenantId(tenantIdStr);
//        if (sysExpenseMerge!=null) {
//            if (StringUtils.isNotBlank(sysExpenseMerge.getThisMonthEletableNumber())) {
//                sysExpenseMerge.setLastMonthEletableNumber(sysExpenseMerge.getThisMonthEletableNumber());
//            }
//            if (StringUtils.isNotBlank(sysExpenseMerge.getThisMonthWatableNumber())) {
//                sysExpenseMerge.setLastMonthWatableNumber(sysExpenseMerge.getThisMonthWatableNumber());
//            }
//        }

        return toAjax(sysExpenseMergeService.insertSysExpenseMerge(sysExpenseMerge,backlogId,tenantIdStr));
    }
//    ===========================================================以下为监听事件==========================================================


    /**
     * 公摊电度数
     */
    @PostMapping("/apportionElectricNumber")
    @ResponseBody
    public Object apportionElectricNumber(double apportionRatioOver,double electricApportionBaseNumber)
    {
        double realValue = apportionRatioOver*electricApportionBaseNumber;
        double temp = DoubleUtil.round(realValue,2);
        Map map = new HashMap();
        map.put("realValue",realValue);
        map.put("temp",temp);
        return map;
    }
    /**
     * 自用电费
     */
    @PostMapping("/useElectricFee")
    @ResponseBody
    public Object useElectricFee(double useElectricNumber,double electricUninPrice)
    {
        double realValue = useElectricNumber*electricUninPrice;
        double temp = DoubleUtil.round(realValue,2);
        Map map = new HashMap();
        map.put("realValue",realValue);
        map.put("temp",temp);
        return map;
    }
    /**
     * 公摊电费
     */
    @PostMapping("/apportionElectricFee")
    @ResponseBody
    public Object apportionElectricFee(double apportionElectricNumber,double electricUninPrice)
    {
        double realValue = apportionElectricNumber*electricUninPrice;
        double temp = DoubleUtil.round(realValue,2);
        Map map = new HashMap();
        map.put("realValue",realValue);
        map.put("temp",temp);
        return map;
    }

    /**
     * 公摊水度数
     */
    @PostMapping("/apportionWaterNumber")
    @ResponseBody
    public Object apportionWaterNumber(double apportionRatioOver,double waterApportionBaseNumber)
    {
        double realValue = apportionRatioOver*waterApportionBaseNumber;
        double temp = DoubleUtil.round(realValue,2);
        Map map = new HashMap();
        map.put("realValue",realValue);
        map.put("temp",temp);
        return map;
    }
    /**
     * 自用水费
     */
    @PostMapping("/useWaterFee")
    @ResponseBody
    public Object useWaterFee(double useWaterNumber,double waterUninPrice)
    {
        double realValue = useWaterNumber*waterUninPrice;
        double temp = DoubleUtil.round(realValue,2);
        Map map = new HashMap();
        map.put("realValue",realValue);
        map.put("temp",temp);
        return map;
    }
    /**
     * 租金90%
     */
    @PostMapping("/ninetyPercentRealMonthlyFee")
    @ResponseBody
    public Object ninetyPercentRealMonthlyFee(double realMonthlyRentFee)
    {
        double realValue = realMonthlyRentFee*0.9;
        double temp = DoubleUtil.round(realValue,2);
        Map map = new HashMap();
        map.put("realValue",realValue);
        map.put("temp",temp);
        return map;
    }

    /**
     * 公摊水费
     */
    @PostMapping("/apportionWaterFee")
    @ResponseBody
    public Object apportionWaterFee(double apportionWaterNumber,double waterUninPrice)
    {
        double realValue = apportionWaterNumber*waterUninPrice;
        double temp = DoubleUtil.round(realValue,2);
        Map map = new HashMap();
        map.put("realValue",realValue);
        map.put("temp",temp);
        return map;
    }
    /**
     * 本月用电
     */
    @PostMapping("/useElectricNumber")
    @ResponseBody
    public Object useElectricNumber(double thisMonthEletableNumber,double lastMonthEletableNumber)
    {
        double realValue = thisMonthEletableNumber-lastMonthEletableNumber;
        double temp = DoubleUtil.round(realValue,2);
        Map map = new HashMap();
        map.put("realValue",realValue);
        map.put("temp",temp);
        return map;
    }
    /**
     * 本月用水
     */
    @PostMapping("/useWaterNumber")
    @ResponseBody
    public Object useWaterNumber(double thisMonthWatableNumber,double lastMonthWatableNumber)
    {
        double realValue = thisMonthWatableNumber-lastMonthWatableNumber;
        double temp = DoubleUtil.round(realValue,2);
        Map map = new HashMap();
        map.put("realValue",realValue);
        map.put("temp",temp);
        return map;
    }
    /**
     * 总用电度数
     */
    @PostMapping("/totalElectricNumber")
    @ResponseBody
    public Object totalElectricNumber(double useElectricNumber,double apportionElectricNumber)
    {
        double realValue = useElectricNumber+apportionElectricNumber;
        double temp = DoubleUtil.round(realValue,2);
        Map map = new HashMap();
        map.put("realValue",realValue);
        map.put("temp",temp);
        return map;
    }
    /**
     * 总用水度数
     */
    @PostMapping("/totalWaterNumber")
    @ResponseBody
    public Object totalWaterNumber(double useWaterNumber,double apportionWaterNumber)
    {
        double realValue = useWaterNumber+apportionWaterNumber;
        double temp = DoubleUtil.round(realValue,2);
        Map map = new HashMap();
        map.put("realValue",realValue);
        map.put("temp",temp);
        return map;
    }
    /**
     * 水电费合计
     */
    @PostMapping("/totalUtilityFee")
    @ResponseBody
    public Object totalUtilityFee(double useElectricFee,double useWaterFee,double apportionElectricFee,double apportionWaterFee)
    {
        double realValue = useElectricFee+useWaterFee+apportionElectricFee+apportionWaterFee;
        double temp = DoubleUtil.round(realValue,2);
        Map map = new HashMap();
        map.put("realValue",realValue);
        map.put("temp",temp);
        return map;
    }
    /**
     * 自用水电费合计
     */
    @PostMapping("/useTotalUtilityFee")
    @ResponseBody
    public Object useTotalUtilityFee(double useElectricFee,double useWaterFee)
    {
        double realValue = useElectricFee+useWaterFee;
        double temp = DoubleUtil.round(realValue,2);
        Map map = new HashMap();
        map.put("realValue",realValue);
        map.put("temp",temp);
        return map;
    }
    /**
     * 水电费合计
     */
    @PostMapping("/apportionTotalUtilityFee")
    @ResponseBody
    public Object apportionTotalUtilityFee(double apportionElectricFee,double apportionWaterFee)
    {
        double realValue = apportionElectricFee+apportionWaterFee;
        double temp = DoubleUtil.round(realValue,2);
        Map map = new HashMap();
        map.put("realValue",realValue);
        map.put("temp",temp);
        return map;
    }
    /**
     * 本月实收金额合计
     */
    @PostMapping("/totalMonthRealFee")
    @ResponseBody
    public Object totalMonthRealFee(double totalUtilityFee,double realPropertyFee,double realMonthlyRentFee,double wlanFee)
    {
        double realValue = totalUtilityFee+realPropertyFee+realMonthlyRentFee+wlanFee;
        double temp = DoubleUtil.round(realValue,2);
        Map map = new HashMap();
        map.put("realValue",realValue);
        map.put("temp",temp);
        return map;
    }
    /**
     * 租金折扣
     */
    @PostMapping("/discount")
    @ResponseBody
    public Object discount(double discount,double monthlyRentFee)
    {
        double realValue = discount/100*monthlyRentFee;
        realValue = DoubleUtil.round(realValue,2);
        Map map = new HashMap();
        map.put("realValue",realValue);
        return map;
    }


}
